package com.xuyuan.valid;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidator;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * Hibernate Validator校验工具类
 */
public class ValidatorUtils {

    private static final Validator validator1;
    private static final Validator validator2;


    static {
        // 校验所有的参数
        validator1 = Validation.buildDefaultValidatorFactory().getValidator();
        // 快速失败模式
        validator2 = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    }

    public static String validatedAll(Object object, Class... groups) {
        List<String> errorMessageList = new ArrayList<>();
        // 3.对参数上的注解进行验证
        Set<ConstraintViolation<Object>> violations = validator1.validate(object, groups);
        // 4.获取校验结果
        for (ConstraintViolation<Object> constraintViolation : violations) {
            errorMessageList.add(constraintViolation.getMessage());
        }
        return errorMessageList.toString();
    }

    public static String validatedFailFast(Object object, Class... groups) {
        List<String> errorMessageList = new ArrayList<>();
        Set<ConstraintViolation<Object>> violations = validator2.validate(object, groups);
        for (ConstraintViolation<Object> constraintViolation : violations) {
            errorMessageList.add(constraintViolation.getMessage());
        }
        return errorMessageList.toString();
    }
}
